﻿<?php
@session_start();

require_once("../../class/mysql.class.php");

  $obj = new Mysql();
  
  $obj -> set_table('user_login');
  $obj -> set_colone("(`*`)");
  $obj -> set_variables(" id_login = '" . $_SESSION["id"] . "' ");
  $user = $obj -> select_enregistrement();

	$id_article = $_REQUEST["ref_article"]; 
	//$type_id = $_REQUEST["id_type"]; 
	//$emplacement_id = $_REQUEST["id_emplacement"]; 
	//$id_fournisseur = $_REQUEST["id_fournisseur"]; 
	$quantite = $_REQUEST["qte"];  
	//$prix = $_REQUEST["prix"]; 
	//$id_unit_stockage = $_REQUEST["unit"];
	//$id_type_monnaie = $_REQUEST["type_monnaie"]; 
	$note = $_REQUEST["comment"];
	$d = $_REQUEST["dateAdd"];
	//$dat =explode('/', $d);
	$dateAdd = $d;//$dat['1'].'/'.$dat['0'].'/'.$dat['2'];
	//echo $dateAdd;
	
	$id_user = $user['id_login'];
	$req="SELECT Quantite,designation From st_article WHERE id_article=".$id_article;
	$obj = new Mysql ();
	$resultEn = mysql_query($req);
	$rowEn = mysql_fetch_array($resultEn);
	echo $rowEn['Quantite'];
	echo $rowEn["designation"];
	if((int)$rowEn['Quantite']<(int)$quantite){
		echo "im here";
		header('location:../../list_sortie.php?action=error3&page=list_sortie&article='.$rowEn["designation"].'');
		exit();
	}

	if($rowEn['Quantite']==0){
		echo "im here";
		header('location:../../list_sortie.php?action=error1&page=list_sortie&article='.$rowEn["designation"].'');
		exit();
	}
	if($rowEn['Quantite']<=0){
		echo "im here";
		header('location:../../list_sortie.php?action=error2&page=list_sortie&article='.$rowEn["designation"].'');
		exit();
	}
	$Qte_stock_ancien=$rowEn['Quantite'];
	$Qte_stock = $Qte_stock_ancien - $quantite; 
	echo $Qte_stock;
		$sql = "INSERT INTO `st_attr_sortie` (`id_sortie`, `id_article`, `Qte`, `Date_cmd`, `note`,`id_user`,`last_modif`,`last_user_modif`,`id_unite`)  VALUES 
			('', '".$id_article."', '".$quantite."',
			 '".$dateAdd."', '".$note."','".$id_user."','".date('d/m/Y')."','".$id_user."', '".$_POST['id_unite']."');";
			echo $sql;
			if(mysql_query($sql)){
				$reqInsert = "UPDATE st_article SET Quantite='".$Qte_stock."' WHERE id_article='".$id_article."'";
				mysql_query($reqInsert);
			}


	//Test if ref existe than update 
		$rq_test = "select * from st_sortie where id_article = ".$id_article;
		echo "<br>-----<br>";
		echo $rq_test;
		echo "<br>-----<br>";
		$res = mysql_query($rq_test);
		$vartest = null;
		while ($d = mysql_fetch_array($res)) {
			$vartest .= $d['id_article'];
		}
		//nouvelle entree
		if($vartest==null){
			$s = "INSERT INTO `st_sortie` (`id`,`id_article`, `date`) VALUES ('','".$id_article."', '".date('d/m/Y H:i:s')."');";
				echo $s;
				mysql_query($s);
		}
		// update existant avec la 
		else{
			$reqUpdate = "UPDATE st_sortie SET date='".date('d/m/Y H:i:s')."' WHERE id_article='".$id_article."'";
			echo "<br>-----<br>";
			echo $reqUpdate;
			echo "<br>-----<br>";
			mysql_query($reqUpdate);
		}
	header('location:../../list_sortie.php?action=added&page=list_sortie');
	

